package com.jier.service.impl;

import com.jier.common.Page;
import com.jier.common.Result;
import com.jier.common.util.StringUtil;
import com.jier.dao.SystemPermissionDao;
import com.jier.dto.SystemPermissionResultDto;
import com.jier.dto.SystemRolePermissionResultDto;
import com.jier.entities.SystemPermission;
import com.jier.service.ISystemPermissionService;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author jie_r
 * @date 2018/03/18
 */
@Service
public class SystemPermissionServiceImpl extends BaseServiceImpl<SystemPermissionDao, SystemPermission> implements ISystemPermissionService {
    @Override
    public Result<SystemPermissionResultDto> getSystemPermissions(Integer moduleId, Page page) throws Exception {
        com.github.pagehelper.Page<SystemPermissionResultDto> listPage = getPageHelper(page).doSelectPage(() -> mapper.getSystemPermissions(moduleId));
        return getRecordPage(listPage, page);
    }

    @Override
    public SystemPermission getSystemPermissionByNumber(String code) throws Exception {
        Example example = getExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("code", code);
        return getUniqueByExample(example);
    }

    @Override
    public SystemPermission getSystemModuleByName(String name, Integer moduleId) throws Exception {
        Example example = getExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("name", name);
        criteria.andEqualTo("moduleId", moduleId);
        return getUniqueByExample(example);
    }

    @Override
    public SystemPermission getSystemPermissionLast(Integer moduleId) throws Exception {
        Example example = getExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("moduleId", moduleId);
        example.setOrderByClause("sort_order desc");
        List<SystemPermission> systemPermissions = getByExample(example);
        if (StringUtil.isEmptyList(systemPermissions)) {
            return null;
        }
        return systemPermissions.get(0);
    }

    @Override
    public List<SystemRolePermissionResultDto> getSystemPermissionByRoleId(Integer roleId) throws Exception {
        return mapper.getSystemPermissionByRoleId(roleId);
    }
}
